package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.common.Result;
import com.example.demo.entity.ExInfo;
import com.example.demo.entity.ExLetters;
import com.example.demo.entity.ExTask;
import com.example.demo.entity.SysUser;
import com.example.demo.exception.CustomException;
import com.example.demo.mapper.ExInfoMapper;
import com.example.demo.mapper.ExLettersMapper;
import com.example.demo.mapper.ExTaskMapper;
import com.example.demo.service.ExTaskService;
import com.example.demo.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.util.*;

@RestController
@RequestMapping("/exTask")
public class ExTaskController extends BaseController{

    @Resource
    ExTaskMapper exTaskMapper;

    @Resource
    ExInfoMapper exInfoMapper;

    @Resource
    ExLettersMapper exLettersMapper;

    @Autowired
    ExTaskService exTaskService;

    @PostMapping
    public Result<?> save(@RequestBody ExTask exTask, HttpServletRequest request) {
        exTask.setCreateTime(new Date());
        if (StrUtil.isNotBlank(exTask.getFileUrl())){
            String classificationName=exTask.getType();
            Integer letterId=exTask.getLetterId();
            ExInfo exInfo=exInfoMapper.selectByTypeAndName(classificationName,letterId);
            exInfo.setIsFinished(1);
            exInfoMapper.updateById(exInfo);
            Integer num=exInfoMapper.selectUnfinished(letterId);
            ExLetters exLetters=exLettersMapper.selectByLetterId(letterId);
            exLetters.setIncomplete(num);
            exLettersMapper.updateById(exLetters);
        }
        exTaskMapper.insert(exTask);
        return Result.success();
    }

    @PutMapping
    public Result<?> update(@RequestBody ExTask exTask,HttpServletRequest request) {
        SysUser user = TokenUtils.getUserInfo(request);
        if (user == null)
            return Result.error("500", "未获取到user信息");
        if (StrUtil.isNotBlank(exTask.getFileUrl())){
            String classificationName=exTask.getType();
            Integer letterId=exTask.getLetterId();
            ExInfo exInfo=exInfoMapper.selectByTypeAndName(classificationName,letterId);
            exInfo.setIsFinished(1);
            exInfoMapper.updateById(exInfo);
            Integer num=exInfoMapper.selectUnfinished(letterId);
            ExLetters exLetters=exLettersMapper.selectByLetterId(letterId);
            exLetters.setIncomplete(num);
            exLettersMapper.updateById(exLetters);
        }
        exTask.setUpdateUser(user.getUsername());
        exTask.setUpdateTime(new Date());
        exTaskMapper.updateById(exTask);
        return Result.success();
    }

    @Transactional
    @DeleteMapping("/{ids}")
    public Result<?> delete(@PathVariable @NotBlank String ids, HttpServletRequest request) {
        SysUser user = TokenUtils.getUserInfo(request);
        if (user == null)
            return Result.error("500", "未获取到user信息");
        List<String> idList = Arrays.asList(ids.split(","));
        for (String ID : idList) {
            ExTask exTaskInfo = exTaskMapper.selectById(ID);
            Optional.ofNullable(exTaskInfo).orElseThrow(() ->  new CustomException("500001","该数据不存在"));
            exTaskInfo.setUpdateUser(user.getUsername());
            exTaskInfo.setUpdateTime(new Date());
            exTaskMapper.updateById(exTaskInfo);
            exTaskMapper.deleteById(exTaskInfo.getId());
        }
        return Result.success("删除成功");
    }

//    @DeleteMapping("/{id}")
//    public Result<?> delete(@PathVariable Integer id) {
//        financeMapper.deleteById(id);
//        return Result.success();
//    }


    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Integer id) {
        return Result.success(exTaskMapper.selectById(id));
    }

/**
 * 
 * @author fqc
 * @date 2023/12/7 16:19
 * @param pageNum 页码
 * @param pageSize 数量
 * @param letterId 项目名称
 * @return com.example.demo.common.Result<?>
 */
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String letterId) {
        LambdaQueryWrapper<ExTask> wrapper = Wrappers.<ExTask>lambdaQuery();
        if (StrUtil.isBlank(letterId)) {
            return Result.success(null);
        }
        if (StrUtil.isNotBlank(letterId)) {
            wrapper.eq(ExTask::getLetterId, letterId);
        }
//        if(StrUtil.isNotBlank(startTime )|| StrUtil.isNotBlank(endTime)){
//            wrapper.and(q -> {
//                if(StrUtil.isNotBlank(startTime)) {
//                    q.ge(FiFinance::getPayTime, startTime);
//                }
//                if(StrUtil.isNotBlank(endTime)){
//                    q.le(FiFinance::getPayTime,endTime);
//                }
//            });
//        }
        Page<ExTask> taskPage = exTaskMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(taskPage);
    }

}
